#region Usings

using System;
using System.Linq;
using log4net;
using Karma.Framework.Core.IoC;
using Karma.Framework.Core.Metadata.Mapping;
using Karma.Framework.Core.Repository;
using Karma.Framework.Core.Security;
using Spring.Expressions;

#endregion

namespace Karma.Framework.Core.Metadata
{
    public class QueryFinder
    {
        private static ILog LOG = LogManager.GetLogger(typeof(QueryFinder).Name);

        private static IRepository<Query> _Repo;
        protected static IRepository<Query> Repo
        {
            get
            {
                if (_Repo == null)
                {
                    _Repo = IoCFactory.Resolve<IRepository<Query>>();
                }
                return _Repo;
            }
        }

        public static QuerySpecification BuscaConsulta(QuerySpecification specification)
        {
            if (LOG.IsDebugEnabled)
            {
                LOG.Debug(string.Format("Query buscado : {0}", specification.Query));
            }
            var consulta = Repo.Get(Int64.Parse(specification.Query));
            if (consulta == null)
            {
                throw new SecurityException(string.Format(
                                                "La consulta con Id {0} no se encuentra configurada.",
                                                specification.Query));
            }
            if (LOG.IsDebugEnabled)
            {
                LOG.Debug(string.Format("El Query encontrado: {0}", consulta.Consulta));
            }
            specification.Query = consulta.Consulta;
            specification.Metadata = consulta;

            // procesa parametros
            if (consulta.Parametros != null && consulta.Parametros.Count > 0)
            {
                specification.Parameters = new object[consulta.Parametros.Count];
                for (var i = 0; i < consulta.Parametros.Count; i++)
                {
                    var p = consulta.Parametros[i];
                    specification.Parameters[i] = ExpressionEvaluator.GetValue(Context.User, p.Expression);
                }
            }

            return specification;
        }
    }
}